package com.tool.cn.model;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
 * 监听方法执行超时
 * 
 * @author wangzh
 * 2018年2月1日 下午5:28:36
 */
public class TimeOutModel {
	
	public void main(){
		
		String context="";
		ExecutorService es = Executors.newSingleThreadExecutor();
        try {
			Future<String> future=es.submit(new TaskThread());
			context = future.get(2, TimeUnit.SECONDS);
		} catch (ExecutionException e) {
			e.printStackTrace();
		} catch (TimeoutException e) {
			System.out.println("运行超时");
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} finally{
			es.shutdownNow();
		}
        System.out.println(context);
	}
	
	private class TaskThread implements Callable<String> {
		@Override
		public String call(){
			String context="nihao";
			try {
				Thread.sleep(2000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}

			return context;
		}

	}

}
